package com.e2j.lib;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;

/**
 * TODO
 *
 * @author 杨永良
 * @date 2022/8/5 19:06
 **/
public class ExcelLibHttpLoader {

    static final Logger logger = (Logger) LoggerFactory.getLogger(ExcelLibHttpLoader.class);

    /**
     * 连接主机服务超时时间
     */
    int connectTimeout = 35000;
    /**
     * 请求超时时间
     */
    int connectionRequestTimeout = 35000;
    /**
     * 数据读取超时时间
     */
    int socketTimeout = 60000;

    /**
     * 配置请求参数设置
     */
    RequestConfig requestConfig;

    /**
     * 服务器ip地址
     */
    String host = "";

    public ExcelLibHttpLoader(String host){
        this.host = host;
    }

    public String getUrl(String questUrl, Map<String,String> params, Map<String,String> headers){
        String url = host + questUrl;

        //创建httpClient实例
        CloseableHttpClient client = HttpClients.createDefault();

        //创建一个uri对象
        URIBuilder uriBuilder = null;
        try {
            uriBuilder = new URIBuilder(url);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            logger.error("创建url失败:" + questUrl);
            logger.error(e.getMessage());
            logger.error(e.getReason());
            return null;
        }

        //塞入form参数
        if(params!=null){
            for (Map.Entry<String, String> entry : params.entrySet()) {
                uriBuilder.addParameter(entry.getKey(), entry.getValue());
                //uriBuilder.addParameter("account", "123");
            }
        }

        //创建httpGet远程连接实例,这里传入目标的网络地址
        HttpGet httpGet = null;
        try {
            httpGet = new HttpGet(uriBuilder.build());
        } catch (URISyntaxException e) {
            e.printStackTrace();
            logger.error("创建httpGet远程连接实例失败:" + questUrl);
            logger.error(e.getMessage());
            logger.error(e.getReason());
            return null;
        }

        // 设置请求头信息
        if(headers!=null){
            for(Map.Entry<String,String> entry : headers.entrySet()){
                httpGet.setHeader(entry.getKey(), entry.getValue());
                //httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            }
        }

        // 设置配置请求参数(没有可忽略)
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)
                .setConnectionRequestTimeout(connectionRequestTimeout)
                .setSocketTimeout(socketTimeout)
                .build();
        // 为httpGet实例设置配置
        httpGet.setConfig(requestConfig);
        //执行请求
        CloseableHttpResponse response = null;
        String jsonStr = "";
        try {
            response = client.execute(httpGet);
            //获取Response状态码
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println(statusCode);
            logger.info("连接[" + questUrl + "] statusCode：" + statusCode);
            //获取响应实体, 响应内容
            HttpEntity entity = response.getEntity();
            //通过EntityUtils中的toString方法将结果转换为字符串
            jsonStr = EntityUtils.toString(entity);
            //System.out.println(jsonStr);
            response.close();
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("Get请求失败:" + questUrl);
            logger.error(e.getMessage());
            return null;
        }

        return jsonStr;
    }


}
